package com.kestrel.space.user.handler;

import com.alibaba.fastjson.JSON;
import com.kestrel.space.common.utils.Result;
import com.kestrel.space.common.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author GSZ
 * explain: 认证异常处理, 登陆失败
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // 设置响应的结果 HttpStatus.UNAUTHORIZED = 401
        // 转换为json
        String jsonString = JSON.toJSONString(Result.fail(HttpStatus.UNAUTHORIZED.value() + "用户认证失败请查询登陆!"));
        // 使用工具类设置响应数据
        WebUtils.renderString(httpServletResponse, jsonString);
    }

}